﻿using Newtonsoft.Json;
using RestSharp;

namespace RuoVea.Iot.MqttClient.Server;

/// <summary>
/// 
/// </summary>
public class ApiClient
{
    private readonly IRestClient _restClient;
    /// <summary>
    /// 
    /// </summary>
    /// <param name="baseUrl"></param>
    public ApiClient(string baseUrl = null)
    {
        var options = string.IsNullOrEmpty(baseUrl)
              ? new RestClientOptions()
              : new RestClientOptions(baseUrl)
              {
                  ThrowOnAnyError = false,
                  Timeout = TimeSpan.FromSeconds(10000) // 默认10秒超时
              };

        _restClient = new RestClient(options)
            .AddDefaultHeader(KnownHeaders.Accept, "application/json")
            .AddDefaultHeader(KnownHeaders.ContentType, "application/json");
    }
    ///
    public async Task<(HttpResponseMessage response, Dictionary<string, string> headersDict)> SendRequestAsync(ReqMqttPayloadDto payload)
    {
        if (payload?.Data == null)
            throw new ArgumentNullException(nameof(payload.Data));

        var request = new RestRequest(payload.Data.Url, GetMethod(payload.Data.Method));

        if (payload.Data.Headers != null)
        {
            foreach (var header in payload.Data.Headers)
            {
                request.AddHeader(header.Key, header.Value);
            }
        }

        if (payload.Data.Data != null &&
           (payload.Data.Method.Equals("POST", StringComparison.OrdinalIgnoreCase) ||
            payload.Data.Method.Equals("PUT", StringComparison.OrdinalIgnoreCase)))
        {
            request.AddJsonBody(JsonConvert.SerializeObject(payload.Data.Data));
        }

        var response = await _restClient.ExecuteAsync(request);
        return  ConvertToHttpResponseMessage(response);
    }

    private static Method GetMethod(string method)
    {
        return method?.ToUpper() switch
        {
            "GET" => Method.Get,
            "POST" => Method.Post,
            "PUT" => Method.Put,
            "DELETE" => Method.Delete,
            _ => throw new NotSupportedException($"Unsupported HTTP Method: {method}")
        };
    }

    /// <summary>
    /// 
    /// </summary>
    /// <param name="restResponse"></param>
    /// <returns></returns>
    private static   (HttpResponseMessage response, Dictionary<string, string> headersDict) ConvertToHttpResponseMessage(RestResponse restResponse)
    {
        var httpResponse = new HttpResponseMessage(restResponse.StatusCode)
        {
            Content = new StringContent(restResponse.Content ?? (restResponse.ErrorMessage ?? string.Empty), System.Text.Encoding.UTF8, "application/json"),
            //RequestMessage= new HttpRequestMessage { Content = new StringContent(restResponse.ErrorMessage ?? string.Empty, System.Text.Encoding.UTF8, "application/json"), }
        };
        if(restResponse.Headers==null) return (httpResponse,null);
        foreach (var header in restResponse.Headers)
        {
            if (header.Value != null)
            {
                httpResponse.Headers.TryAddWithoutValidation(header.Name, header.Value.ToString());
            }
        }
        var headersDict = ConvertHeadersToDictionary(restResponse.Headers);
        return  (httpResponse,headersDict);
    }

    private static Dictionary<string, string> ConvertHeadersToDictionary(IReadOnlyCollection<HeaderParameter> headers)
    {
        var dictionary = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);

        if (headers != null)
        {
            foreach (var header in headers)
            {
                // 将每个header的所有值合并为逗号分隔的字符串
                dictionary[header.Name] = string.Join(", ", header.Value);
            }
        }
        return dictionary;
    }
}